// 云函数入口文件
const cloud = require('wx-server-sdk')
const TcbRouter = require('tcb-router');
const axios = require('axios');
const md5 = require('md5-node');
//京东垃圾分类API配置
let jdaicofig = {
    secretkey: '71f2412730dc362e4e74c70eeb210c48',
    appkey: 'c4a78411138c3aad25275f94eec2b1bc'
}
//在设置 env 时指定 cloud.DYNAMIC_CURRENT_ENV 常量 (需 SDK v1.1.0 或以上) ，这样云函数内发起数据库请求、存储请求或调用其他云函数的时候，默认请求的云环境就是云函数当前所在的环境
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})
// 云函数入口函数
exports.main = async (event, context) => {
    const wxContext = cloud.getWXContext()
    let {
        APPID,
        OPENID
    } = wxContext
    const app = new TcbRouter({
        event
    })
    //提供通过文本进行垃圾分类查询的能力
    app.router('garbageTextSearch', async (ctx, next) => {
        let {
            text
        } = event
        let timestamp = Date.now()
        let sign = md5(jdaicofig.secretkey + timestamp)
        ctx.body = axios.post(`https://aiapi.jd.com/jdai/garbageTextSearch?appkey=${jdaicofig.appkey}&timestamp=${timestamp}&sign=${sign}`, {
            text: text,
            cityId: '110000'
        }).then(res => res.data.result)
    })
    //获取用户openID
    app.router('openId', async (ctx, next) => {
        ctx.body = {
            openId: OPENID
        }
    })
    return app.serve()
}